package com.example.addressdemo.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import com.example.addressdemo.Address.Contact;

/**
 * Created by 十田田 on 2021/5/25.
 */

public class DBAdapter {
    private static final String DB_NAME = "address.db";
    private static final String DB_TABLE = "contact";
    private static final int DB_VERSION = 1;

    public static final String KEY_NAME = "name";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_WORK = "work";
    public static final String KEY_HOME = "home";

    private SQLiteDatabase db;//声明SQLiteDatabase实例，该类中封装对数据库的操作方法
    private Context context;
    private DBOpenHelper dbOpenHelper;//帮助类，用于建立、更新和打开数据库

    public DBAdapter(Context _context) {
        context = _context;
    }

    private static class DBOpenHelper extends SQLiteOpenHelper { //数据库帮助类
        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table " + DB_TABLE + "("
                + KEY_NAME + " text primary key,"
                + KEY_PHONE + " text not null,"
                + KEY_WORK + " text,"
                + KEY_HOME + " text);"; //创建表的SQL命令

        @Override
        public void onCreate(SQLiteDatabase _db) { //在数据库第一次建立时调用，一般用来建表以及初始化工作
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {  //用于删除旧表并将数据转移到新版
            _db.execSQL("DROP TABLE IF EXISTS" + DB_TABLE);
            onCreate(_db);
        }

    }

    public void open() throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            Toast.makeText(context, "Create/open Successed", Toast.LENGTH_SHORT).show();
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
        }
    }

    public long insert(ContentValues contentValues) throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            return db.insert(DB_TABLE, null, contentValues);
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
            return 0;
        }
    }

    public long update(ContentValues contentValues) throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            String name=contentValues.getAsString("name");
            return db.update(DB_TABLE, contentValues,KEY_NAME+"='"+name+"'",null);
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
            return 0;
        }
    }

    public long delete(String name) throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            return db.delete(DB_TABLE,KEY_NAME+"='"+name+"'",null);
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
            return 0;
        }
    }
    private Contact[] ConvertToContact(Cursor cursor){
        int resultCounts=cursor.getCount();
        if(resultCounts==0||!cursor.moveToFirst()){
            return null;
        }
        Contact[] contacts=new Contact[resultCounts];
        for(int i=0;i<resultCounts;i++){
            contacts[i]=new Contact();
            contacts[i].name=cursor.getString(0);
            contacts[i].phone=cursor.getString(cursor.getColumnIndex(KEY_PHONE));
            contacts[i].work=cursor.getString(cursor.getColumnIndex(KEY_WORK));
            contacts[i].home=cursor.getString(cursor.getColumnIndex(KEY_HOME));
            cursor.moveToNext();
        }
        return contacts;
    }

    public Contact[] getOneData(String name){
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            Log.d("getonedata",name);
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            Cursor results=db.query(DB_TABLE,new String[]{KEY_NAME,KEY_PHONE,KEY_WORK,KEY_HOME},KEY_NAME+"='"+name+"'",null,null,null,null);
            return ConvertToContact(results);
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
            return null;
        }
    }

    public Contact[] getAllData(){
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase(); //建立和打开可读写的数据库实例，一但调用成功，数据库实例将被缓存
            Cursor results=db.query(DB_TABLE,new String[]{KEY_NAME,KEY_PHONE,KEY_WORK,KEY_HOME},null,null,null,null,KEY_NAME+" ASC");
            return ConvertToContact(results);
        } catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase(); //获得只读数据库实例
            return null;
        }
    }



    public void close() {//关闭数据库
        if (db != null) {
            db.close();
            db = null;
        }
    }




}



